package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {

    private List<Map<String,Object>> dbList=new ArrayList<>();
    public AjaxController(){
        Map<String,Object> map=new HashMap<>();
        map.put("id","100");
        map.put("name","家用电器");
        map.put("parentId",null);
        map.put("remark","电器相关等");
        map.put("createdTime",new Date());
        dbList.add(map);
    }

    @GetMapping("/doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        return dbList;
    }
    @PostMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        map.put("createdTime",new Date());
        dbList.add(map);
        return "save ok";
    }

    @DeleteMapping("/doAjaxDelete")
    public String doAjaxDelete(String id){
        //获取迭代器对象，然后迭代List集合
        Iterator it=dbList.iterator();
         while (it.hasNext()) {
             Map<String,Object> map=(Map<String,Object>)it.next();
            if(map.get("id").equals(id)){
                //dbList.remove(map);
                it.remove();//通过迭代器执行删除操作
            }
        }
        return "delete ok";
    }

    @PutMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> updatemap){
        Iterator it=dbList.iterator();
        while (it.hasNext()) {
            Map<String,Object> map=(Map<String,Object>)it.next();
            if(map.get("id").equals(updatemap.get("id"))){
                map.put("name",updatemap.get("name"));
                map.put("remark",updatemap.get("remark"));
            }
        }
        return "update ok";
    }
    @CrossOrigin// @CrossOrigin 注解描述的方法支持跨域访问
    @RequestMapping("/doAjaxGet01")
    public String doAjaxGet01(){
        return "Response Result of Ajax Get Request 01";
    }
}
